//
//  GQHReceiptController.m
//  Xanthium
//
//  Created by GuanQinghao on 12/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View

#pragma mark Controller
#import "GQHReceiptController.h"

#pragma mark CocoaPods
#import <TZImagePickerController.h>

#pragma mark ----------Header End----------


static CGFloat const singleMargin = 16.0f;
static CGFloat const doubleMargin = 2 * singleMargin;


@interface GQHReceiptController () <TZImagePickerControllerDelegate> {
    
#pragma mark Data
    /// 标记上传图片
    int imageCount;
    /// 选择的要上传的图片
    __block NSMutableArray *imageArray;
#pragma mark View
    UIView *receiptView;
}

@end


@implementation GQHReceiptController

#pragma mark --Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    [self loadUserInterface];
    
    imageArray = [NSMutableArray array];
    [self layoutViewWithImages:imageArray];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"回执单";
    [self.qh_rightButton setTitle:@"确定" forState: UIControlStateNormal];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate

#pragma mark --TargetMethod
- (void)qh_clickedRightButton:(UIButton *)sender {
    
    if (!(imageArray && imageArray.count > 0)) {
        
        [self showToastWithText:@"请上传回执单"];
        return;
    }
    
    [self qh_loadLoadingView];
    [self removePicturesWithSuccess:^(NSNumber *code, NSString *message, NSDictionary *data) {
        
        if (0 == [code integerValue]) {
            
            imageCount = 0;
            for (UIImage *image in imageArray) {
                
                [self uploadImage:image success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                    
                    if (0 == [code integerValue]) {
                        
                        imageCount += 1;
                    }
                    
                    if (imageCount == imageArray.count) {
                        DLog(@"图片上传成功，修改订单状态");
                        
                        [self updateOrderState];
                    }
                }];
            }
        } else {
            [self qh_removedLoadingView];
            [self showToastWithText:@"图片上传失败，请稍后重试"];
        }
    }];
}

#pragma mark --PrivateMethod
/// 选择图片
- (IBAction)selectedPhotos:(id)sender {
    
    GQH_WEAKSELF;
    TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        DLog(@"选择图片完成,上传图片");
        
        if (photos && photos.count > 0) {
            
            [imageArray addObjectsFromArray:photos];
            [weakSelf layoutViewWithImages:imageArray];
        }
    }];
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
    
//    GQH_WEAKSELF;
//    TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:self];
//    imagePickerController.allowTakePicture = NO;
//    [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//        DLog(@"选择图片完成,上传图片");
//
//        imageArray = [NSMutableArray arrayWithArray:photos];
//        [weakSelf layoutViewWithImages:imageArray];
//    }];
//    [self presentViewController:imagePickerController animated:YES completion:nil];
}
/// 上传之前删除已有图片
- (void)removePicturesWithSuccess:(void(^)(NSNumber *code, NSString *message, NSDictionary *data))success{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:_qh_orderModel.qh_orderNumber forKey:@"waybillAwb"];
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/buWaybill/1/deletePicture"];
    [GQHNetHelper qh_requestGET:APIURLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
        
        success(code,message,nil);
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}
/// 上传图片 每次一张
- (void)uploadImage:(UIImage *)image success:(void(^)(NSNumber *code, NSString *message, NSDictionary *data))success {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"driverId"];
    [parameters setObject:_qh_orderModel.qh_orderNumber forKey:@"waybillAwb"];
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/buWaybill/1/uploadPicture"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:APIURLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImagePNGRepresentation(image);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        [formData appendPartWithFileData:data name:@"attachment" fileName:fileName mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self qh_removedLoadingView];
        if (success) {
            
            NSNumber *responseCode = [responseObject objectForKey:@"code"];
            NSString *responseMessage = [responseObject objectForKey:@"msg"];
            NSDictionary *responseData = [responseObject objectForKey:@"data"];
            
            success(responseCode,responseMessage,responseData);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self qh_removedLoadingView];
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}
/// 修改订单状态
- (void)updateOrderState {
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:USER_GET_ID forKey:@"driverId"];
    [para setObject:_qh_orderModel.qh_orderNumber forKey:@"waybillAwb"];
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/buWaybill/1/waitArrive"];
    [GQHNetHelper qh_requestGET:APIURLString parameters:para success:^(NSNumber *code, NSString *message, NSDictionary *data) {
        DLog(@"%@---%@---%@",code,message,data);
        
        if (0 == [code integerValue]) {
            
            [self showToastWithText:@"卸货成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            
            [self showToastWithText:message];
        }
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View
- (void)loadUserInterface {
    
    UIView *titleView = [[UIView alloc] init];
    titleView.backgroundColor = kLightGrayColor;
    [self.view addSubview:titleView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view).with.offset(self.view.qh_statusBarHeight + self.view.qh_navigationBarHeight);
        make.left.and.right.mas_equalTo(self.view);
        make.height.mas_equalTo(40);
    }];
    
    UILabel *orderNumberLabel = [[UILabel alloc] init];
    orderNumberLabel.font = kSmallerFont;
    orderNumberLabel.text = [NSString stringWithFormat:@"运单号：%@",_qh_orderModel.qh_orderNumber];
    orderNumberLabel.backgroundColor = kClearColor;
    [titleView addSubview:orderNumberLabel];
    [orderNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(titleView).with.inset(10);
        make.left.and.right.mas_equalTo(titleView).with.inset(singleMargin);
        make.height.mas_equalTo(20);
    }];
    
    receiptView = [[UIView alloc] init];
    receiptView.backgroundColor = kWhiteColor;
    [self.view addSubview:receiptView];
    [receiptView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(titleView.mas_bottom);
        make.left.and.right.mas_equalTo(self.view);
        make.height.mas_equalTo(300);
    }];
}

- (void)layoutViewWithImages:(NSMutableArray<UIImage *> *)images {
    
    [receiptView qh_removeAllSubviews];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectedPhotos:)];
    
    CGFloat itemX = singleMargin;
    CGFloat itemY = 10;
    CGFloat itemWidth = 0.25 * (self.view.qh_width - doubleMargin - 30);
    CGFloat itemHeight = itemWidth;
    
    if (6 == images.count) {
        /// 六张图
        for (int i = 0; i < images.count; i++) {
            
            CGRect frame = CGRectMake(itemX  + (itemWidth + 10) * (i%4), itemY + (itemHeight + 10) * (i/4), itemWidth, itemHeight);
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
            imageView.image = images[i];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tapGesture];
            [receiptView addSubview:imageView];
        }
    } else if (0 == images.count){
        /// 没有图
        CGRect frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = [UIImage imageNamed:@"add_photo"];
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:tapGesture];
        [receiptView addSubview:imageView];
    } else {
        /// 一到五张图
        for (int i = 0; i < images.count; i++) {
            
            CGRect frame = CGRectMake(itemX  + (itemWidth + 10) * (i%4), itemY + (itemHeight + 10) * (i/4), itemWidth, itemHeight);
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
            imageView.image = images[i];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tapGesture];
            [receiptView addSubview:imageView];
        }
        
        CGRect frame = CGRectMake(itemX  + (itemWidth + 10) * (images.count%4), itemY + (itemHeight + 10) * (images.count/4), itemWidth, itemHeight);
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = [UIImage imageNamed:@"add_photo"];
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:tapGesture];
        [receiptView addSubview:imageView];
    }
}

@end
